<template>
  <div class="card" style="max-width:520px;margin:40px auto;padding:20px;">
    <h2 style="margin-top:0;">个人信息</h2>
    
    <div v-if="loading" style="text-align:center;padding:40px;">
      加载中...
    </div>
    
    <div v-else-if="!user" style="text-align:center;padding:40px;">
      <div>无法获取用户信息</div>
      <button class="btn" style="margin-top:16px;" @click="loadUserInfo">重新加载</button>
    </div>
    
    <form v-else class="space-y" @submit.prevent="updateProfile">
      <div class="space-y">
        <label class="muted">用户名</label>
        <input class="input" v-model="formData.username" disabled />
      </div>
      
      <div class="space-y">
        <label class="muted">邮箱</label>
        <input class="input" type="email" v-model="formData.email" required />
      </div>
      
      <div class="space-y">
        <label class="muted">电话</label>
        <input class="input" v-model="formData.phone" required />
      </div>
      
      <div style="color:#ef4444;" v-if="error">{{ error }}</div>
      <div style="color:#10b981;" v-if="successMessage">{{ successMessage }}</div>
      
      <button class="btn" type="submit" :disabled="updating">
        {{ updating ? '更新中...' : '保存修改' }}
      </button>
    </form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      user: null,
      formData: {
        id: '',
        username: '',
        email: '',
        phone: ''
      },
      loading: false,
      updating: false,
      error: '',
      successMessage: ''
    }
  },
  
  async created() {
    await this.loadUserInfo()
  },
  
  methods: {
    async loadUserInfo() {
      const user = JSON.parse(localStorage.getItem('user')||'null')
      if (!user) {
        location.hash = '#/login'
        return
      }
      
      this.loading = true
      this.error = ''
      
      try {
        const res = await fetch(`/api/v1/user/profile?userId=${user.id}`)
        if (res.ok) {
          this.user = await res.json()
          // 填充表单数据
          this.formData = {
            id: this.user.id,
            username: this.user.username,
            email: this.user.email,
            phone: this.user.phone
          }
        } else {
          this.error = '无法获取用户信息'
        }
      } catch (error) {
        this.error = '网络错误，请稍后再试'
      } finally {
        this.loading = false
      }
    },
    
    async updateProfile() {
      this.updating = true
      this.error = ''
      this.successMessage = ''
      
      try {
        const res = await fetch('/api/v1/user/profile', {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(this.formData)
        })
        
        if (res.ok) {
          const updatedUser = await res.json()
          this.user = updatedUser
          
          // 更新localStorage中的用户信息
          const currentUser = JSON.parse(localStorage.getItem('user')||'null')
          if (currentUser) {
            const updatedLocalUser = {
              ...currentUser,
              email: updatedUser.email,
              phone: updatedUser.phone
            }
            localStorage.setItem('user', JSON.stringify(updatedLocalUser))
            // 触发storage事件，通知其他组件更新用户状态
            window.dispatchEvent(new Event('storage'))
          }
          
          this.successMessage = '个人信息更新成功'
          // 3秒后清除成功提示
          setTimeout(() => {
            this.successMessage = ''
          }, 3000)
        } else {
          this.error = '更新失败，请稍后再试'
        }
      } catch (error) {
        this.error = '网络错误，请稍后再试'
      } finally {
        this.updating = false
      }
    }
  }
}
</script>